import axios from "axios";
// import { ElMessage } from 'element-plus'

const BaseUrl = 'http://106.13.143.56:8080'
const httpInstance = axios.create({
  baseURL: BaseUrl,
  timeout: 3000,
  headers: {'Content-Type': 'application/json'}
});
// instance.defaults.headers.common['Authorization'] = sessionStorage.getItem("token");
// 添加请求拦截器
httpInstance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
	// console.log("请求拦截器",config)
	if(sessionStorage.getItem("token")){
		config.headers.token=sessionStorage.getItem("token")
	}
    return config;
  }, function (error) {
    // 对请求错误做些什么
	// console.log("请求拦截器error",error)
    return Promise.reject(error);
  });

// 添加响应拦截器
httpInstance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
	// console.log("响应拦截器",response)
    return response;
  }, function (error) {
    // 对响应错误做点什么
	// console.log("响应拦截器error",error)
	if(error.code="ERR_BAD_REQUEST"){
		// ElMessage.error("请核对您的请求地址")
	}
    return Promise.reject(error);
  });

function merge(data){//{a:1}
	let dataArr=[]
	for(let k in data){
		dataArr.push(k+"="+data[k])
	}
	return dataArr.join("&");
}

function merge2(data){
	let dataArr=[];
	for(let k in data){
		dataArr.push(data[k])
	}
	return dataArr.join("/");
}

//1：？传参
//2：对象传参
//3:/传参

async function httpRequest(url,method,type,data){
	let realUrl=url
	let config={
		method:method,
		url:realUrl
	}
	if(data){
		switch(type){
			case 1:config.url=realUrl+"?"+merge(data);break;
			case 2:config.data=data;break;
			case 3:config.url=realUrl+"/"+merge2(data);break;
		}
		
	}
	
	
	
	try{
		let res=await httpInstance(config);
		// console.log('res',res);
		if(res.data.code == 200){
			return res
		}else{
			// ElMessage.error("失败:"+res.data.msg)
			return res
		}
	}catch(e){
		// ElMessage.error("请求错误")
	}
}


export default class Request{
	static async postRequest(url,type,data){
		return await httpRequest(url,"post",type,data);
	}
	static async getRequest(url,type,data){
		return await httpRequest(url,"get",type,data);
	}
} 




